package com.hc.programming.bean;

import java.util.List;

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public ListNode(List<Integer> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        ListNode t = this;
        t.val = list.get(0);
        int len = list.size();
        for (int i = 1; i < len; i++) {
            t.next = new ListNode(list.get(i));
            t = t.next;
        }
    }

    /**
     * 环形链表
     *
     * @param list 元素列表
     * @param pos  最后一个节点指向的位置
     */
    public ListNode(List<Integer> list, int pos) {
        if (list == null || list.isEmpty()) {
            return;
        }
        ListNode t = this;
        t.val = list.get(0);
        int len = list.size();
        for (int i = 1; i < len; i++) {
            t.next = new ListNode(list.get(i));
            t = t.next;
        }
        if (pos >= 0) {
            ListNode head = this;
            for (int i = 0; i < pos; i++) {
                if (head.next == null) break;
                head = head.next;
            }
            t.next = head;
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (ListNode t = this;
                ;
             t = t.next) {
            sb.append(t.val).append(",");
            if (t.next == null) {
                break;
            }
        }
        int length = sb.length();
        if (length > 1) {
            sb.delete(length - 1, length);
        }
        sb.append("]");
        return sb.toString();
    }
}